


package jnpf.zcasset.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.xuyanwu.spring.file.storage.FileInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.vo.DownloadVO;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.config.ConfigValueUtil;
import jnpf.exception.DataException;
import jnpf.permission.entity.UserEntity;
import jnpf.util.*;
import jnpf.zcasset.entity.ZcAssetMortgageEntity;
import jnpf.zcasset.model.zcassetmortgage.ZcAssetMortgageForm;
import jnpf.zcasset.model.zcassetmortgage.ZcAssetMortgageInfoVO;
import jnpf.zcasset.model.zcassetmortgage.ZcAssetMortgageListVO;
import jnpf.zcasset.model.zcassetmortgage.ZcAssetMortgagePagination;
import jnpf.zcasset.service.ZcAssetMortgageService;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 资产抵押
 *
 * @版本： V3.2.0
 * @版权： 智果云科技（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期：
 */
@Slf4j
@RestController
@Api(tags = "资产抵押", value = "zc")
@RequestMapping("/api/zc/ZcAssetMortgage")
public class ZcAssetMortgageController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private ConfigValueUtil configValueUtil;

    @Autowired
    private UserProvider userProvider;


    @Autowired
    private ZcAssetMortgageService zcAssetMortgageService;


    /**
     * 列表
     *
     * @param zcAssetMortgagePagination
     * @return
     */
    @ApiOperation("获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody ZcAssetMortgagePagination zcAssetMortgagePagination) throws IOException {
        List<ZcAssetMortgageEntity> list = zcAssetMortgageService.getList(zcAssetMortgagePagination);
        //处理id字段转名称，若无需转或者为空可删除

        List<ZcAssetMortgageListVO> listVO = JsonUtil.getJsonToList(list, ZcAssetMortgageListVO.class);
        for (ZcAssetMortgageListVO zcAssetMortgageVO : listVO) {
            zcAssetMortgageVO.setAssetId_name(generaterSwapUtil.getDynName("612769091110831365", "ASSET_NAME", "id", "", zcAssetMortgageVO.getAssetId(), false));

            zcAssetMortgageVO.setMortgageCompany_name(generaterSwapUtil.getDicName(zcAssetMortgageVO.getMortgageCompany(), "610824142995849541"));

            zcAssetMortgageVO.setMortgageStartDate_name(zcAssetMortgageVO.getMortgageStartDate());

            zcAssetMortgageVO.setMortgageEndDate_name(zcAssetMortgageVO.getMortgageEndDate());

            zcAssetMortgageVO.setMortgageAmount_name(zcAssetMortgageVO.getMortgageAmount());

            zcAssetMortgageVO.setRemark_name(zcAssetMortgageVO.getRemark());

            zcAssetMortgageVO.setAttachmentUrls_name(generaterSwapUtil.getFileNameInJson(zcAssetMortgageVO.getAttachmentUrls()));

            //子表数据转换
        }

        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(zcAssetMortgagePagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    /**
     * 创建
     *
     * @param zcAssetMortgageForm
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Valid ZcAssetMortgageForm zcAssetMortgageForm) throws DataException {
        boolean b = zcAssetMortgageService.checkForm(zcAssetMortgageForm, 0);
        if (b) {
            return ActionResult.fail("单行输入不能重复");
        }
        String mainId = RandomUtil.uuId();

        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        ZcAssetMortgageEntity entity = JsonUtil.getJsonToBean(zcAssetMortgageForm, ZcAssetMortgageEntity.class);
        entity.setId(mainId);
        zcAssetMortgageService.save(entity);


        return ActionResult.success("创建成功");
    }


    /**
     * 模板下载
     *
     * @return
     */
    @ApiOperation("模板下载")
    @GetMapping("/TemplateDownload")
    public ActionResult<DownloadVO> TemplateDownload() {
        UserInfo userInfo = userProvider.get();
        DownloadVO vo = DownloadVO.builder().build();
        try {
            vo.setName("职员信息.xlsx");
            vo.setUrl(UploaderUtil.uploaderFile("/api/Common/DownloadModel?encryption=", userInfo.getId() + "#" + "职员信息.xlsx" + "#" + "Temporary"));
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
        }
        return ActionResult.success(vo);
    }

    /**
     * 导出Excel
     *
     * @return
     */
    @ApiOperation("导出Excel")
    @PostMapping("/Actions/Export")
    public ActionResult Export(@RequestBody ZcAssetMortgagePagination zcAssetMortgagePagination) throws IOException {
        if (StringUtil.isEmpty(zcAssetMortgagePagination.getSelectKey())) {
            return ActionResult.fail("请选择导出字段");
        }
        List<ZcAssetMortgageEntity> list = zcAssetMortgageService.getTypeList(zcAssetMortgagePagination, zcAssetMortgagePagination.getDataType());
        //处理id字段转名称，若无需转或者为空可删除

        List<ZcAssetMortgageListVO> listVO = JsonUtil.getJsonToList(list, ZcAssetMortgageListVO.class);
        for (ZcAssetMortgageListVO zcAssetMortgageVO : listVO) {
            zcAssetMortgageVO.setAssetId_name(generaterSwapUtil.getDynName("612769091110831365", "ASSET_NAME", "id", "", zcAssetMortgageVO.getAssetId(), false));
            zcAssetMortgageVO.setMortgageCompany_name(generaterSwapUtil.getDicName(zcAssetMortgageVO.getMortgageCompany(), "610824142995849541"));
            zcAssetMortgageVO.setMortgageStartDate_name(zcAssetMortgageVO.getMortgageStartDate());
            zcAssetMortgageVO.setMortgageEndDate_name(zcAssetMortgageVO.getMortgageEndDate());
            zcAssetMortgageVO.setMortgageAmount_name(zcAssetMortgageVO.getMortgageAmount());
            zcAssetMortgageVO.setRemark_name(zcAssetMortgageVO.getRemark());
            zcAssetMortgageVO.setAttachmentUrls_name(generaterSwapUtil.getFileNameInJson(zcAssetMortgageVO.getAttachmentUrls()));

            //子表数据转换
        }

        //转换为map输出
        List<Map<String, Object>> mapList = JsonUtil.getJsonToListMap(JsonUtil.getObjectToStringDateFormat(listVO, "yyyy-MM-dd HH:mm:ss"));
        mapList.stream().forEach(map -> {
            Map<String, Object> map2 = new HashMap<>();
            map.putAll(map2);
        });
        String[] keys = !StringUtil.isEmpty(zcAssetMortgagePagination.getSelectKey()) ? zcAssetMortgagePagination.getSelectKey().split(",") : new String[0];
        UserInfo userInfo = userProvider.get();
        DownloadVO vo = this.creatModelExcel(configValueUtil.getTemporaryFilePath(), mapList, keys, userInfo);
        return ActionResult.success(vo);
    }

    //导出表格
    public DownloadVO creatModelExcel(String path, List<Map<String, Object>> list, String[] keys, UserInfo userInfo) {
        DownloadVO vo = DownloadVO.builder().build();
        List<ExcelExportEntity> entitys = new ArrayList<>();
        if (keys.length > 0) {
            for (String key : keys) {
                switch (key) {
                    case "assetId":
                        entitys.add(new ExcelExportEntity("资产信息", "assetId_name"));
                        break;
                    case "mortgageCompany":
                        entitys.add(new ExcelExportEntity("抵押单位", "mortgageCompany_name"));
                        break;
                    case "mortgageStartDate":
                        entitys.add(new ExcelExportEntity("抵押开始日期", "mortgageStartDate_name"));
                        break;
                    case "mortgageEndDate":
                        entitys.add(new ExcelExportEntity("抵押结束日期", "mortgageEndDate_name"));
                        break;
                    case "mortgageAmount":
                        entitys.add(new ExcelExportEntity("抵押金额", "mortgageAmount_name"));
                        break;
                    case "remark":
                        entitys.add(new ExcelExportEntity("备注", "remark_name"));
                        break;
                    case "attachmentUrls":
                        entitys.add(new ExcelExportEntity("附件", "attachmentUrls_name"));
                        break;
                    default:
                        break;

                }
            }
            List<String> keylist = new ArrayList<>();
            for (String key : keys) {
                keylist.add(key);
            }
        }

        ExportParams exportParams = new ExportParams(null, "表单信息");
        exportParams.setType(ExcelType.XSSF);
        try {
            @Cleanup Workbook workbook = new HSSFWorkbook();
            if (entitys.size() > 0) {
                if (list.size() == 0) {
                    list.add(new HashMap<>());
                }
                workbook = ExcelExportUtil.exportExcel(exportParams, entitys, list);
            }
            String fileName = "表单信息" + DateUtil.dateNow("yyyyMMdd") + "_" + RandomUtil.uuId() + ".xlsx";

            String temporaryFilePath = configValueUtil.getTemporaryFilePath();
            MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
            FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
            vo.setName(fileInfo.getFilename());
            vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
            e.printStackTrace();
        }
        return vo;
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<ZcAssetMortgageInfoVO> info(@PathVariable("id") String id) {
        ZcAssetMortgageEntity entity = zcAssetMortgageService.getInfo(id);
        ZcAssetMortgageInfoVO vo = JsonUtil.getJsonToBean(entity, ZcAssetMortgageInfoVO.class);

        //子表
        //副表
        return ActionResult.success(vo);
    }

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @ApiOperation("表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<ZcAssetMortgageInfoVO> detailInfo(@PathVariable("id") String id) {
        ZcAssetMortgageEntity entity = zcAssetMortgageService.getInfo(id);
        ZcAssetMortgageInfoVO vo = JsonUtil.getJsonToBean(entity, ZcAssetMortgageInfoVO.class);

        //子表数据转换

        //附表数据转换

//添加到详情表单对象中
        vo.setAssetId(generaterSwapUtil.getDynName("612769091110831365", "ASSET_NAME", "id", "", vo.getAssetId(), false));

        vo.setMortgageCompany(generaterSwapUtil.getDicName(vo.getMortgageCompany(), "610824142995849541"));

        vo.setMortgageStartDate(vo.getMortgageStartDate());

        vo.setMortgageEndDate(vo.getMortgageEndDate());

        vo.setMortgageAmount(vo.getMortgageAmount());

        vo.setRemark(vo.getRemark());

        vo.setAttachmentUrls(generaterSwapUtil.getFileNameInJson(vo.getAttachmentUrls()));


        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @param zcAssetMortgageForm
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid ZcAssetMortgageForm zcAssetMortgageForm) throws DataException {
        boolean b = zcAssetMortgageService.checkForm(zcAssetMortgageForm, 1);
        if (b) {
            return ActionResult.fail("单行输入不能重复");
        }
        UserInfo userInfo = userProvider.get();
        ZcAssetMortgageEntity entity = zcAssetMortgageService.getInfo(id);
        if (entity != null) {
            ZcAssetMortgageEntity subentity = JsonUtil.getJsonToBean(zcAssetMortgageForm, ZcAssetMortgageEntity.class);
            boolean b1 = zcAssetMortgageService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        ZcAssetMortgageEntity entity = zcAssetMortgageService.getInfo(id);
        if (entity != null) {
            zcAssetMortgageService.delete(entity);

        }
        return ActionResult.success("删除成功");
    }


}
